package com.kly.sc.api.application.controller.im;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.config.AppConfigs;
import com.kly.sc.api.application.controller.im.request.IMUserInfoRequest;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.utils.BaseComponent;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.infras.enums.RestCodeEnum;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.infras.handler.ApiResponse;
import com.kly.sc.api.integration.IMService;
import com.kly.sc.api.integration.RCClient;
import com.kly.user.dto.UserConversationVO;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.enums.PushNotificationType;
import com.kly.user.service.AuthLoginService;
import com.kly.user.service.OtherService;
import com.kly.user.service.UserConversationService;
import com.kly.user.service.UserService;
import io.rong.models.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/auth")
@Slf4j
public class IMController extends BaseComponent {

    @Resource
    UserService userService;
    @Resource
    AuthLoginService authLoginService;
    @Resource
    private OtherService otherService;
    @Resource
    IMService imService;
    @Resource
    UserConversationService userConversationService;

    /**
     * 获取融云平台会话token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getIMtoken", method = RequestMethod.POST)
    public ApiResponse getIMtoken(){

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();

        Map<String, Object> resultMap = new HashMap<>(1);

        // 判断是否存在融云平台token, 若存在直接返回
        final String rongCloudToken = RpcUtils.getResult(authLoginService.getRongCloudToken(userCode));
        if (StringUtils.isNotBlank(rongCloudToken)) {
            resultMap.put("token", rongCloudToken);
            return ApiResponse.ok(resultMap);
        }

        // RPC获取用户信息
        UserInfoDto userInfoDto = getCurrentUserInfo(userCode);
        // 使用userInfoDto注册融云账户，注册成功后拿到token
        String token = imService.getToken(userCode, userInfoDto.getNickName(), userInfoDto.getAvatarUrl());
        // 封装token返回给客户端
        resultMap.put("token", token);

        return ApiResponse.ok(resultMap);
    }

    @ResponseBody
    @RequestMapping(value = "/conversation/list", method = RequestMethod.POST)
    public Response listConversation(){

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        final Response<List<UserConversationVO>> response = userConversationService.getAllConversationByUserCode(userCode);
        // 此处无数据或失败，只会引起展示异常，对业务逻辑无影响
        if (Objects.isNull(response) || !response.isSuccess()) {
            return Response.ok();
        }
        return Response.ok(response.getData());
    }

    /**
     * 修改用户头像
     * @return
     */
    @SignIgnore
    @ResponseBody
    @RequestMapping(value = "/modifyUserInfo", method = RequestMethod.POST)
    public Response modifyUserInfo(@RequestBody IMUserInfoRequest request){
        // 获取用户token
        final String rongCloudToken = RpcUtils.getResult(authLoginService.getRongCloudToken(request.getUserCode()));

        // 已在IM平台注册过，直接修改用户信息
//        if (StringUtils.isNotBlank(rongCloudToken)) {
//            final Result result = rcClient.modifyUser(request.getUserCode(), request.getNickname(), request.getAvatarUrl());
//            log.info("ModifyUserInfoResult, userCode:{}, result:{}", request.getUserCode(), JSONObject.toJSONString(result));
//            if (Objects.isNull(result) || result.getCode() != 200) {
//                log.error("invoke rongCloud server exception,resultCode={},errorMessage={}", result.getCode(), result.getErrorMessage());
//                throw new ApplicationException(RestCodeEnum.RC_PARAMETER_ERROR + " errorMsg: " + result.getErrorMessage());
//            }
//        }
//        // 未注册过，需要在IM平台注册账号
//        else {
//            final String token = imService.getToken(request.getUserCode(), request.getNickname(), request.getAvatarUrl());
//            if (StringUtils.isBlank(token)) {
//                log.error("invoke rongCloud server exception, params:{}", JSONObject.toJSONString(request));
//                throw new ApplicationException(RestCodeEnum.RC_PARAMETER_ERROR);
//            }
//        }

        final String token = imService.getToken(request.getUserCode(), request.getNickname(), request.getAvatarUrl());
        if (StringUtils.isBlank(token)) {
            log.error("invoke rongCloud server exception, params:{}", JSONObject.toJSONString(request));
            throw new ApplicationException(RestCodeEnum.RC_PARAMETER_ERROR);
        }


        // IM注册成功后，通知客户端
//        log.info("====pushNotificationStart, userInfo:{}", JSONObject.toJSONString(request));
        final Response response = otherService.pushNotification(request.getUserCode(), PushNotificationType.PUSH_TO_CHAT_LIST.getType());
//        log.info("====pushNotificationStart, userInfo:{}", JSONObject.toJSONString(response));
        if (Objects.nonNull(response) && response.isSuccess()) {
            return Response.ok();
        }

        return Response.error("Update account information failed!");
    }


    /**
     * 获取用户信息
     * @param userCode
     * @return
     */
    private UserInfoDto getCurrentUserInfo(String userCode) {
        final UserInfoDto userInfoDto = RpcUtils.getResult(userService.getUserByUserCode(userCode));
        if (Objects.isNull(userInfoDto)) {
            throw new ApplicationException(RestCodeEnum.USER_NOT_EXIST_ERROR);
        }
        return userInfoDto;
    }
}
